﻿using DTcms.Common;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers.Feedback
{
    public class FeedbackController : ManageController
    {
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            ViewBag.action = _action;
            ViewBag.id = _id;
        }

        [ChkAdminScript("plugin_feedback", DTEnums.ActionEnum.View)]
        public ActionResult Feedback_List()
        {
            return View();
        }

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (title like '%" + _keywords + "%' or user_name like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.View)]
        public JsonResult FeedbackList(string keywords,int _site_id=0, int page = 1, int limit = 10)
        {
            string strWhere = "id>0";
            if (_site_id > 0)
            {
                strWhere += " and site_id=" + _site_id;
            }
            strWhere += CombSqlTxt(keywords);
            string strOrder = "is_lock desc,add_time desc";
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            var resultList = bll.GetQueryPage(page, limit, strWhere, strOrder);
            DataTable Items = DataHelper.ListToDataTable(resultList.Items);
            DataTable oldData = Items.Clone();
            if (resultList.TotalItems > 0)
            {
                oldData.Columns.Add("siteTitle", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["user_name"] = item["user_name"];
                    row["title"] = item["title"];
                    row["add_time"] = item["add_time"];
                    row["type"] = item["type"];
                    row["reply_content"] = item["reply_content"];
                    row["is_lock"] = item["is_lock"];
                    row["id"] = item["id"];
                    row["siteTitle"] = new BLL.sites().GetTitle(Utils.ObjToInt(item["site_id"]));
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = resultList.TotalItems });
        }

        [ChkAdminScript("plugin_feedback", DTEnums.ActionEnum.View)]
        public ActionResult Feedback_Edit()
        {
            Model.plugin_feedback model = new Model.plugin_feedback();
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = bll.Get(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        [ChkAdminScript("plugin_feedback2", DTEnums.ActionEnum.View)]
        public ActionResult Feedback_Install()
        {
            BLL.feedbackconfig bll = new BLL.feedbackconfig();
            Model.feedbackconfig model = bll.loadConfig("/plugins/feedback/config/install.config");
            return View(model);
        }

        //保存
        [HttpPost, ValidateInput(false), CustomValidateAntiForgeryToken]
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.Instal)]
        public ActionResult InstallSave(Model.feedbackconfig t)
        {
            BLL.feedbackconfig bll = new BLL.feedbackconfig();
            Model.feedbackconfig model = bll.loadConfig("/plugins/feedback/config/install.config");
            try
            {
                model.bookmsg = Utils.StrToInt(t.bookmsg.ToString(), 0);
                model.booktemplet = t.booktemplet.Trim();
                model.receive = t.receive.Trim();

                bll.saveConifg(model, "/plugins/feedback/config/install.config");
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改留言插件配置信息"); //记录日志
                return Json(new { status = 1, msg = "修改留言插件配置信息成功！", url = "../feedback/feedback_install" });
            }
            catch
            {
                return Json(new { status = 0, msg = "文件写入失败，请检查文件夹权限！", url = "back" });
            }
        }

        #region 审核
        [HttpPost]
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.Audit)]
        public JsonResult FeedbackAudit(List<int> ids)
        {
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            foreach (int id in ids)
            {
                bll.UpdateFile("id=" + id, "is_lock=0");
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "审核留言"); //记录日志
            return Json(new { status = 1, msg = "批量审核成功！" });
        }
        #endregion

        #region 彻底删除
        [HttpPost]
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.Delete)]
        public JsonResult FeedbackDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除留言成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion

        #region 修改管理员状态
        [HttpPost]
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.Edit)]
        public JsonResult FeedbackLock(int id, bool is_lock)
        {
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            if (bll.UpdateFile("id=" + id, "is_lock=" + (is_lock ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "状态修改成功！" });
            }
            return Json(new { status = 0, msg = "状态修改失败！" });
        }
        #endregion

        #region 个别字段修改
        [HttpPost]
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.Edit)]
        public JsonResult FeedbackFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion

        [HttpPost, CustomValidateAntiForgeryToken]
        [ChkAdminJson("plugin_feedback", DTEnums.ActionEnum.Reply)]
        public ActionResult FeedbackSave(Model.plugin_feedback t)
        {
            BLL.plugin_feedback bll = new BLL.plugin_feedback();
            Model.plugin_feedback model = bll.Get(_id);
            model.reply_content = Utils.ToHtml(t.reply_content);
            model.reply_time = DateTime.Now;
            if (bll.Update(model))
            {
                AddAdminLog(DTEnums.ActionEnum.Reply.ToString(), "回复留言插件内容：" + model.title); //记录日志
            }
            else
            {
                return Json(new { status = 0, msg = "保存过程中发生错误！", url = "back" });
            }
            return Json(new { status = 1, msg = "添加链接成功！", url = "../feedback/feedback_list" });
        }
    }
}
